package com.aimls.monitor;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class FileScheduler {
	/*
	 * 定时器
	 */
	private final Timer timer;

	public FileScheduler() {
		timer = new Timer();
	}

	public FileScheduler(boolean isDaemon) {
		/*
		 * 是否为守护线程
		 */
		timer = new Timer(isDaemon);
	}

	public void schedule(Runnable task, TimeStep step) {
		Date time = step.next();
		SchedulerTimerTask timeTask = new SchedulerTimerTask(task, step);
		// 安排在指定的时间 time 执行指定的任务 timetask
		timer.schedule(timeTask, time);
	}

	private void reSchedule(Runnable task, TimeStep step) {
		Date time = step.next();
		SchedulerTimerTask timeTask = new SchedulerTimerTask(task, step);
		// 安排在指定的时间 time 执行指定的任务 timetask
		timer.schedule(timeTask, time);
	}

	/**
	 * 停止当前定时器
	 */
	public void cancle() {
		timer.cancel();
	}

	private class SchedulerTimerTask extends TimerTask {
		private Runnable task;
		private TimeStep step;

		public SchedulerTimerTask(Runnable task, TimeStep step) {
			this.task = task;
			this.step = step;
		}

		@Override
		public void run() {
			// 执行指定任务
			task.run();
			// 继续重复执行任务
			reSchedule(task, step);
		}
	}
}
